package com.itcs.app.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itcs.app.service.PayService;
import com.itcs.app.service.TransJournalService;
import com.itcs.app.tran.SendBoxSocket;
import com.itcs.app.util.PayChannelCode;
import com.itcs.app.util.PayResult;
import com.itcs.app.util.PayStatus;
import com.itcs.app.util.PayType;
import com.itcs.box.domain.BoxResponse;
import com.itcs.box.util.BoxResUtils;
import com.itcs.box.util.LogUtils;
import com.itcs.trading.mapper.ExitWhitelistOpHisMapper;
import com.itcs.trading.mapper.TransJournalMapper;
import com.itcs.trading.mapper.UserAccountInfoMapper;
import com.itcs.trading.mapper.UserAccountOpHisMapper;
import com.itcs.trading.model.ExitWhitelistOpHis;
import com.itcs.trading.model.TransJournal;
import com.itcs.trading.model.UserAccountInfo;
import com.itcs.trading.model.UserAccountOpHis;

/**
 * 支付订单 zhaojins 20171223
 */

@Service
public class PayServiceImpl implements PayService {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private UserAccountInfoMapper userAccountInfoMapper;

	@Autowired
	private TransJournalMapper transJournalMapper;
	@Autowired
	private TransJournalService transJournalService;

	@Autowired
	private SendBoxSocket sendBoxSocket;

	@Autowired
	private UserAccountOpHisMapper userAccountOpHisMapper;
	
	@Autowired
	private ExitWhitelistOpHisMapper exitWhitelistOpHisMapper;

	/**
	 * APP支付回调
	 */
	@Override
	public Map<String, String> payResult(Map<String, String> paramMap) {
		// TODO Auto-generated method stub
		Map<String, String> resqMap = new HashMap<String, String>();
		String transacSeq = paramMap.get("traderecordsId");
		TransJournal traderecords = transJournalService.selectByTransNo(transacSeq);

		// 根据订单ID查询itcs_trans_jnl,获取支付状态 1待支付 2支付成功 3支付失败 4支付异常,
		// Map<String, Object> trans = transJournalMapper.selectByPlayerId((String)
		// paramMap.get("traderecordsId"));
		if (traderecords == null) {// 查不到数据，返回相关信息
			resqMap.put("mess", "通过seq查不到对象序列号，非法查询");
			resqMap.put("state", "0");// 失败
		} else {
			// TODO 改成常量
			if (traderecords.getPayState() == PayStatus.支付成功 || traderecords.getPayState() == PayStatus.车道确认支付完成) {// 支付成功
				resqMap.put("mess", "订单已被支付，支付异常");
				resqMap.put("state", "0");// 失败
			} else {// 1、3、4状态 ，实行余额扣款
					// 判断金额,如果账户余额<通行费额应付金额,提示余额不足，否则进行扣款交易
				UserAccountInfo userInfo = userAccountInfoMapper
						.selectByPrimaryKey(Long.valueOf(paramMap.get("userId")));// 获取账户余额
				if (userInfo == null) {
					resqMap.put("mess", "查不到对象，非法查询");
					resqMap.put("state", "0");// 失败
				} else {
					BigDecimal oldBalance = (BigDecimal) userInfo.getAccountBalance();// 账户余额
					BigDecimal balance = (BigDecimal) traderecords.getTollFare();// 通行费应付金额
					int amountFlag = oldBalance.compareTo(balance);
					// System.out.println("userAmount==" + oldBalance + "tollFareAmount" + balance +
					// "amountFlag" + amountFlag);
					if (amountFlag == 0 || amountFlag == 1) {// 账户余额大于或等于通行费应付金额
						traderecords.setPayerId(PayType.自由钱包);
						traderecords.setPayState(PayStatus.支付成功);// 更新订单状态
						traderecords.setUserId(userInfo.getUserId());
						transJournalMapper.updateByPrimaryKey(traderecords);
						// TransJournal.pay;
						// =============================账户历史变动表================================
						// 将数据插入的账户历史变动表中?????????,需记录到记录表串
						BigDecimal endBalance = oldBalance.subtract(balance);// 计算账户余额

						UserAccountOpHis userAccountOpHis = new UserAccountOpHis();
						userAccountOpHis.setTransNo(transacSeq);
						userAccountOpHis.setTransTimestamp(new Date());
						userAccountOpHis.setUserId(userInfo.getUserId());// 用户ID
						userAccountOpHis.setChangeBalance(balance);// 消费
						userAccountOpHis.setOldBalance(oldBalance);// 期初余额
						userAccountOpHis.setNowBalance(endBalance);// 期末余额
						userAccountOpHis.setResume("通讯盒：" + traderecords.getTerminalNo());
						userAccountOpHisMapper.insert(userAccountOpHis);
						// ==========================账户历史变动表===================================

						// 7、判断交易是否支付，没有则直接扣款
						userInfo.setAccountBalance(endBalance);// 进行扣款
						// user.setUpdateTime(new Date());
						userAccountInfoMapper.payBalance(userInfo);

						logger.info(LogUtils.build("appPay", "app手动支付", "APP支付手动扣款成功。transacSeq：" + transacSeq
								+ ",UserId:" + userInfo.getUserId() + ",余额变动[" + oldBalance + "->" + endBalance + "]"));

						//修改为支付成功，清空白名单==================2018-04-20
						// 11、清空某车牌的白名单
						ExitWhitelistOpHis clear = new ExitWhitelistOpHis();
						clear.setCarPlate(traderecords.getCarPlate());
						exitWhitelistOpHisMapper.deleteWhitelis(clear);
						logger.info("删除已支付车牌白名单,车牌号为["+traderecords.getCarPlate()+"]");
						//修改为支付成功，清空白名单==================2018-04-20
						
						// 9、下发2008，通知车道抬杠，等待1008、1009
						BoxResponse response2008 = BoxResUtils.build2008(String.valueOf(traderecords.getTerminalNo()),
								traderecords.getTransNo(), PayResult.成功, PayType.BOX_APP支付, PayChannelCode.自有钱包, null);
						sendBoxSocket.pubsubRes2BoxServer(response2008);

						resqMap.put("mess", "交易成功");
						resqMap.put("state", "1");// 交易成功
					} else {
						resqMap.put("mess", "提示账户余额不足,交易失败");
						resqMap.put("state", "2019");// 失败
					}
				}
			}
		}
		return resqMap;
	}
}
